package com.qiqi.web;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.qiqi.dao.OrderMapper;
import com.qiqi.domain.Order;
import com.qiqi.service.order.OrderService;

@Controller("webOrderControler")
public class OrderController {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderService orderService;
	@RequestMapping("/buy")
	public String toAddOrder(Order order,ModelMap model){
		model.put("order", order);
		return "order/order";
	}
	@SuppressWarnings("deprecation")
	@RequestMapping("/order/add")
	public String addOrder(MultipartFile file1,MultipartFile file2,Order order,HttpServletRequest request,ModelMap model) throws Exception{
		Date today=new Date();
		SimpleDateFormat df=new SimpleDateFormat("yyyyMMdd");
		String path="UID/"+df.format(today);
		String basepath = request.getRealPath(path);
		File dir=new File(basepath);
		if(!dir.exists()){
			dir.mkdir();
		}
		String name1=order.getNum()+"_1"+file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf("."), file1.getOriginalFilename().length());
		String name2=order.getNum()+"_2"+file2.getOriginalFilename().substring(file2.getOriginalFilename().lastIndexOf("."), file2.getOriginalFilename().length());
		File image1=new File(basepath+File.separator+name1);
		File image2=new File(basepath+File.separator+name2);
		FileCopyUtils.copy(file1.getInputStream(),new FileOutputStream(image1));
		FileCopyUtils.copy(file2.getInputStream(),new FileOutputStream(image2));
		order.setPic1(path+"/"+name1);
		order.setPic2(path+"/"+name2);
		order.setState(0);
		order.setCreatetime(today);
		String host = "http://"+request.getLocalAddr();
		orderService.placeOrder(order,host);
		return "order/success";
	}
	@RequestMapping("/order/{id}")
	public String  detail(@PathVariable Integer id,ModelMap model){
		Order order = orderMapper.selectByPrimaryKey(id);
		model.put("order", order);
		return "order/detail";
	}
	
}
